package com.lin.linchatgpt.utils;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.concurrent.atomic.AtomicLong;

//@Component
//@Scope("singleton")
public class CounterService {
    private AtomicLong counter;
    private File file;

    @Value("${counter.file.path}")
    private String filePath;

    @PostConstruct
    public void init() throws IOException {
        file = new File(filePath);
        if (file.exists()) {
            try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
                counter = new AtomicLong(in.readLong());
            }
        } else {
            counter = new AtomicLong();
        }
    }

    public long incrementAndGet() throws IOException {
        long value = counter.incrementAndGet();
        try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
            out.writeLong(value);
        }
        return value;
    }

    public long get() {
        return counter.get();
    }
}
